#include "global_config.h"
#include "public_apis.h"

#define TAG "CLK"

static void drv_sys_tic_update_cb(void *arg)
{
    public_sys_tick_update(SYS_TIC_MS);
}

static void drv_clock_set_systic_en(en_state_t en)
{
    if (en)
        timer_enable(TIMER_SYSTIC);
    else
        timer_disable(TIMER_SYSTIC);
    public_sys_tick_clear();
}

static void sys_tic_sleep_cb(void *arg, size_t len)
{
    drv_clock_set_systic_en(DISABLE);
}

static void sys_tic_wake_cb(void *arg, size_t len)
{
    drv_clock_set_systic_en(ENABLE);
}

void drv_clock_install(void)
{

#if (SYS_FREQ == 16000000)
    SetSysClock(CLK_SOURCE_HSE_16MHz);
#endif
#if (SYS_FREQ == 20000000)
    SetSysClock(CLK_SOURCE_PLL_20MHz);
#endif
#if (SYS_FREQ == 60000000)
    SetSysClock(CLK_SOURCE_PLL_60MHz);
#endif

    timer_init(TIMER_SYSTIC, SYS_TIC_MS, drv_sys_tic_update_cb, NULL); // SYS TIC

    topic_messenger_subscribe(NULL, "sleep", sys_tic_sleep_cb);
    topic_messenger_subscribe(NULL, "wakeup", sys_tic_wake_cb);
}
